#include "http.hpp"

#define WWWROOT "./wwwroot/"
#include "./boost/search.hpp"
#include "./boost/Daemon.hpp"

const std::string input = "./boost/data/raw_html/raw.txt";
//const std::string root_path = "./wwwroot";

std::string RequestStr(const HttpRequest &req) {
    std::stringstream ss;
    ss << req._method << " " << req._path << " " << req._version << "\r\n";
    for (auto &it : req._params) {
        ss << it.first << ": " << it.second << "\r\n";
    }
    for (auto &it : req._headers) {
        ss << it.first << ": " << it.second << "\r\n";
    }
    ss << "\r\n";
    ss << req._body;
    return ss.str();
}
void Hello(const HttpRequest &req, HttpResponse *rsp) 
{
    rsp->SetContent(RequestStr(req), "text/plain");
}
void Login(const HttpRequest &req, HttpResponse *rsp) 
{
    rsp->SetContent(RequestStr(req), "text/plain");
}
void PutFile(const HttpRequest &req, HttpResponse *rsp) 
{
    std::string pathname = WWWROOT + req._path;
    //Util::WriteFile(pathname, req._body);
}
void DelFile(const HttpRequest &req, HttpResponse *rsp) 
{
    rsp->SetContent(RequestStr(req), "text/plain");
}
int main()
{
    HttpServer server(8081);
    Search search;
    search.InitSearch(input);
    server.SetThreadCount(3);
    server.SetBaseDir(WWWROOT);//设置静态资源根目录，告诉服务器有静态资源请求到来，需要到哪里去找资源文件
    server.Get("/hello", Hello);
    server.Post("/login", Login);
    server.Put("/1234.txt", PutFile);
    server.Delete("/1234.txt", DelFile);   
    // 新增 /s 路径的处理函数,处理boost业务
    server.Get("/s", [&search](const HttpRequest &req, HttpResponse *rsp) {
        if (!req.HasParam("word")) {  // 假设 HttpServer 的 Request 类有 has_param 方法
            rsp->SetContent("必须要有搜索关键字!", "text/plain");
            return;
        }
        std::string word = req.GetParam("word");  // 假设有 get_param_value 方法
        std::cout << "用户在搜索：" << word << std::endl;

        // 调用 Search 对象获取 JSON 数据
        // Search search;  // 需要确保 Search 对象已初始化（可能需要全局或成员变量）
        // search.InitSearch(input);  // input 是第一张图中的常量字符串
        std::string json_string = search.get_param_value(word);  // 假设 Search 类有类似方法

        rsp->SetContent(json_string, "application/json");
    });

    server.Listen();
    return 0;
}